package 我的Java学习_算法基础.day_03;

public class _044_逆序对个数 {
    public static void main(String[] args) {
        int[] a = {37, 40, 48, 90, 32, 5, 12, 3, 44, 13};
        System.out.println(reverseOrder1(a));
        System.out.println(reverseOrder2(a));
    }

    private static int reverseOrder1(int[] array) { //暴力解法
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] > array[j]) {
                    count++;
                }
            }
        }
        return count;
    }

    private static int reverseOrder2(int[] array) {     //归并思想
        sort(array,0, array.length-1);
        return niXu;
    }

    private static void sort(int[] array, int begin, int end) {
        if (begin < end) {
            int mid = begin + ((end - begin) >> 1);
            sort(array, begin, mid);
            sort(array, mid + 1, end);
            merge(array, begin, mid, end);
        }
    }
    static int niXu=0;
    private static void merge(int[] array, int begin, int mid, int end) {
        int[] helper = new int[array.length];
        for (int i = begin; i <= end; i++) {
            helper[i] = array[i];
        }
        int left = begin, right = mid + 1;
        int current = begin;
        while ((left <= mid) && (right <= end)) {
            if (helper[left] <= helper[right]) {
                array[current] = helper[left];
                current++;
                left++;
            } else {            //右边小
                array[current] = helper[right];
                current++;
                right++;
                niXu+=mid-left+1;
            }
        }
        //这样做完左侧指针可能没到头，右侧的没到头也没关系
        while (left <= mid) {
            array[current] = helper[left];
            current++;
            left++;
        }

    }
}

